<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>接龙任务管理（Admin Only）</title>
    <!-- Bootstrap 5 CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { background: #f8f9fa; font-size: 1.08rem; }
        .main-container { max-width: 900px; margin: 40px auto; padding: 2rem; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
        @media (max-width: 600px) {
            body { font-size: 0.98rem; }
            .main-container { max-width: 99vw; margin: 10px 1vw; padding: 0.7rem; }
            h2, .h2 { font-size: 1.2rem; }
            .navbar-brand { font-size: 1.1rem; }
            .form-control, .btn, .form-text, th, td { font-size: 0.98rem; }
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">逐光帮会管理系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item"><a class="nav-link" href="/">考勤上传</a></li>
                    <li class="nav-item"><a class="nav-link" href="/attendance_table">总考勤表</a></li>
                    <li class="nav-item"><a class="nav-link active" href="/jielong_admin">接龙任务管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="/jielong/history">接龙历史</a></li>
                </ul>
                <div class="d-flex">
                    <a class="btn btn-outline-secondary me-2" href="/logout">退出登录</a>
                </div>
            </div>
        </div>
    </nav>
    <div class="main-container">
        <h2 class="mb-4 text-center">接龙任务管理（仅管理员）</h2>
        <form id="upload-form" action="/jielong/upload" method="post" class="mb-4">
            <div class="mb-3">
                <label for="raw_text" class="form-label">粘贴接龙原始文本：</label>
                <textarea id="raw_text" name="raw_text" rows="8" class="form-control" required placeholder="请粘贴接龙原始文本"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">提交接龙任务</button>
        </form>
        <hr>
        <h3>查询任务状态</h3>
        <form id="status-form" class="row g-2 align-items-center mb-3" onsubmit="return queryStatus(event)">
            <div class="col-auto">
                <label for="task_id" class="col-form-label">任务ID：</label>
            </div>
            <div class="col-auto">
                <input type="text" id="task_id" name="task_id" class="form-control" required placeholder="请输入任务ID">
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-secondary">查询状态</button>
            </div>
        </form>
        <div id="status-result" class="alert alert-info d-none"></div>
    </div>
    <script>
    // 提交任务后显示任务ID
    document.getElementById('upload-form').onsubmit = async function(event) {
        event.preventDefault();
        const raw_text = document.getElementById('raw_text').value;
        const res = await fetch('/jielong/upload', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ raw_text })
        });
        const data = await res.json();
        let msg = '';
        if (data.task_id) {
            msg = `任务已提交，任务ID：<b>${data.task_id}</b>`;
        } else {
            msg = '提交失败：' + (data.error || '未知错误');
        }
        const statusDiv = document.getElementById('status-result');
        statusDiv.innerHTML = msg;
        statusDiv.classList.remove('d-none');
        statusDiv.classList.remove('alert-danger');
        statusDiv.classList.add('alert-info');
    };

    // 查询任务状态
    async function queryStatus(event) {
        event.preventDefault();
        const task_id = document.getElementById('task_id').value;
        const res = await fetch(`/jielong/status?task_id=${encodeURIComponent(task_id)}`);
        const data = await res.json();
        let msg = '';
        if (data.status) {
            msg = `任务ID：<b>${task_id}</b><br>状态：<b>${data.status}</b>`;
            if (data.status === 'done') {
                if (data.report) {
                    msg += `<br><b>Report：</b><pre>${typeof data.report === 'object' ? JSON.stringify(data.report, null, 2) : data.report}</pre>`;
                }
                if (data.debug_log) {
                    msg += `<br><details><summary><b>Debug日志（点击展开/复制）</b></summary><pre style='max-height:300px;overflow:auto;'>${data.debug_log}</pre></details>`;
                } else {
                    msg += `<br><span class='text-muted'>无Debug日志</span>`;
                }
            } else if (data.status === 'running') {
                msg += '<br><span class="text-info">任务正在运行，请稍后刷新。</span>';
            } else if (data.error) {
                msg += `<br><b>错误：</b>${data.error}`;
            }
        } else {
            msg = '未找到该任务，或查询失败。';
        }
        const statusDiv = document.getElementById('status-result');
        statusDiv.innerHTML = msg;
        statusDiv.classList.remove('d-none');
        statusDiv.classList.remove('alert-info');
        statusDiv.classList.remove('alert-danger');
        if (data.status === 'failed') {
            statusDiv.classList.add('alert-danger');
        } else {
            statusDiv.classList.add('alert-info');
        }
        return false;
    }
    </script>
</body>
</html>
